package com.qianfeng.smsplatform.gateway.filters;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.smsplatform.gateway.cache.ApiMappingCache;
import com.qianfeng.smsplatform.gateway.cache.ApiMappingFilterCache;
import com.qianfeng.smsplatform.gateway.pojo.TApiMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by Jackiechan on 2022/2/14/16:38
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class RoutingFilter extends ZuulFilter {


    private ApiMappingCache apiMappingCache;

    private ApiMappingFilterCache apiMappingFilterCache;


    @Autowired
    public void setApiMappingFilterCache(ApiMappingFilterCache apiMappingFilterCache) {
        this.apiMappingFilterCache = apiMappingFilterCache;
    }
    @Autowired
    public void setApiMappingCache(ApiMappingCache apiMappingCache) {
        this.apiMappingCache = apiMappingCache;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+100+apiMappingFilterCache.getIndex(this.getClass().getSimpleName().toLowerCase());
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean zuulResponse = currentContext.sendZuulResponse();//根据前置过滤器的结果来决定是否启用当前过滤器,前面拦截这个就不执行
        boolean shouldFilter = apiMappingFilterCache.shouldFilter(this.getClass().getSimpleName().toLowerCase());

//        if (!zuulResponse) {
//            return false;
//        }

        return zuulResponse&&shouldFilter;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = context.getRequest();
        String method = httpServletRequest.getParameter("method");
        TApiMapping tApiMapping = apiMappingCache.get(method);

        if (tApiMapping == null) {
            context.setSendZuulResponse(false);
            context.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            context.setResponseBody("请求的服务不存在");
            return null;
        }

        Enumeration<String> parameterNames = httpServletRequest.getParameterNames();//获取到所有传递的参数名
        //name age id  /{id}
        String insideApiUrl = tApiMapping.getInsideApiUrl();//获取到要访问的地址,但是这个地址中可能会存在/{}类型的参数
        System.err.println("替换前的地址" + insideApiUrl);
        //按照我们的要求.我们定义/{}中的参数名叫什么,用户就必须传递对应的参数名
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();//获取到每一个参数名
            //将参数路径替换为当前的具体的请求传递的值
            insideApiUrl=insideApiUrl.replace("{"+paramName+"}",httpServletRequest.getParameter(paramName));
        }
        System.err.println("替换hou ----->的地址" + insideApiUrl);
        //转发到其他的服务
        context.put(FilterConstants.SERVICE_ID_KEY, tApiMapping.getServiceId());
        context.put(FilterConstants.REQUEST_URI_KEY,insideApiUrl);
        return null;
    }
}
